<template>
  <page-view class="page-view page-view-container" :title="false">

    <div slot="headerContent">
      <div class="title">用户管理</div>
    </div>

    <a-card v-permission:permission:menu class="s-card">

      <div class="filter">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">

            <a-row :gutter="48">
              <a-col :md="8" :sm="24">
                <a-form-item label="员工工号">
                  <a-input v-model="queryParam.name" placeholder="请输入" />
                </a-form-item>
              </a-col>

              <!-- <a-col :md="6" :sm="24">
                <a-form-item label="是否启用">
                  <a-select v-model="queryParam.status" placeholder="请选择" default-value="0">
                    <a-select-option value="1">启用</a-select-option>
                    <a-select-option value="2">未启用</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col> -->

              <a-col :md="8" :sm="24">
                <a-form-item label="账户状态">
                  <a-select v-model="queryParam.isLocked" placeholder="请选择" default-value="0">
                    <a-select-option value="1">启用</a-select-option>
                    <a-select-option value="2">禁用</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>

              <a-col :md="8" :sm="24">
                <span class="table-page-search-submitButtons">
                  <a-button class="primary-btn" @click="$refs.table.refresh(true)">查询</a-button>
                  <a-button style="margin-left: 8px" @click="resetForm()">清除查询</a-button>
                </span>
              </a-col>

            </a-row>
            <a-row>
              <a-button type="primary" style="margin-top:20px" @click="handleCreate">新建用户</a-button>
            </a-row>
          </a-form>
        </div>
      </div>

      <div v-permission:permission:menu class="table-container">
        <s-table
          ref="table"
          key="id"
          bordered
          :columns="user && user.permission && user.permission.includes('permission:update') ? columns : columnsBase"
          :data="loadData"
          hide-on-single-page
          show-total
          show-quick-jumper
          class="pagination-container s-table"
        >
          <span slot="action" slot-scope="text, record">
            <a v-if="record.accountNonLocked" class="edit disabled-link no-padding" @click="() => toggle(record)">禁用</a>
            <a v-if="!record.accountNonLocked" class="edit" @click="() => toggle(record)">启用</a>
            <a-divider type="vertical" />
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="resetPassword(record)">重置密码</a>
            <a-divider type="vertical" />
            <a-popconfirm
              overlay-class-name="width-unset"
              title="是否要删除此用户？"
              @confirm="handleDelUser(record)"
            >
              <a class="danger-link no-padding" href="javascript:;">删除</a>
            </a-popconfirm>
            <!-- <a-dropdown>
              <a class="ant-dropdown-link">
                更多 <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a v-if="record.accountNonLocked" class="edit" @click="() => toggle(record)">禁用</a>
                  <a v-if="!record.accountNonLocked" class="edit" @click="() => toggle(record)">恢复</a>
                </a-menu-item>
                <a-menu-item>
                  <a href="javascript:;">删除</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown> -->
          </span>
        </s-table>
      </div>

      <a-modal
        v-model="visible"
        title="新建/编辑用户"
        centered
        style="top: 20px;"
        :width="800"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <a-form :form="form">
          <a-form-item
            v-if="!isCreate"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            label="唯一识别码"
            has-feedback
          >
            <a-input
              id="no"
              v-model="mdl.id"
              placeholder="唯一识别码"
              disabled="disabled"
            />
          </a-form-item>

          <a-form-item
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            label="员工工号"
          >
            <a-input
              v-decorator="[
                'username',
                { initialValue:mdl.username,
                  rules: [{ required: true, message: '员工工号位必填项' },
                          {max:10,message:'名字长度不得超过10个字节'}]}
              ]"
              placeholder="请输入"
            />
          </a-form-item>

          <!-- <a-form-item
            v-if="!isCreate"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            label="是否启用"
            has-feedback
            :validate-status="mdl.enabled==true?'success':'warning'"
          >
            <a-select v-model="mdl.enabled" disabled="disabled">
              <a-select-option :value="true">启用</a-select-option>
              <a-select-option :value="false">未启用</a-select-option>
            </a-select>
          </a-form-item> -->

          <a-form-item
            v-if="!isCreate"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            label="是否禁用"
            has-feedback
            :validate-status="mdl.accountNonLocked==true?'success':'warning'"
          >
            <a-select v-model="mdl.accountNonLocked">
              <a-select-option :value="true">启用</a-select-option>
              <a-select-option :value="false">禁用</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            label="手机号码"
          >
            <a-input
              id="mobile"
              v-decorator="[
                'mobile',
                { initialValue:mdl.mobile,
                  rules: [{ required: true, message: '请输入手机号码' }]}
              ]"
              placeholder="请输入手机号码"
            />
          </a-form-item>

          <a-form-item
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            required="true"
            label="赋予角色"
          >
            <a-select
              id="scope"
              v-decorator="[
                'scope',
                { initialValue:mdl.scope,
                  rules: [{ required: true, message: '请输入手机号码' }]}
              ]"
              mode="multiple"
              style="width: 100%"
            >
              <a-select-option v-for="(action, index) in permissionList" :key="index" :value="action.role.code" :disabled="action.role.code==='EMPLOYEE' || action.role.code==='TEACHER'">{{ permissionMap[action.role.code] }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            v-if="isCreate"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            label="登录密码"
          >
            <div>abc123</div>
          </a-form-item>
        </a-form>
      </a-modal>

      <a-modal
        :visible="resetVisible"
        title="重置密码"
        centered
        style="top: 20px;"
        :width="600"
        @ok="handleReset"
        @cancel="handleCancel"
      >
        <a-form-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          label="请输入密码"
          has-feedback
        >
          <a-input v-model="resetMdl.password" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          label="请确认密码"
          has-feedback
        >
          <a-input v-model="resetMdl.password2" placeholder="请确认密码" />
        </a-form-item>
      </a-modal>

    </a-card>
  </page-view>
</template>

<script>
import { mapState } from 'vuex'
import { STable, PageView } from '@/components'
import moment from 'moment'
// import { getRoleList, getServiceList } from '@/api/manage'

const columnsBase = [
  // {
  //   title: '唯一识别码',
  //   dataIndex: 'id'
  // },
  {
    title: '员工账号',
    dataIndex: 'username'
  },
  // {
  //   title: '是否启用',
  //   dataIndex: 'enabled',
  //   customRender: (value) => { return value ? '启用' : '未启用' }
  // },
  {
    title: '状态',
    dataIndex: 'accountNonLocked',
    customRender: (value) => { return value ? '启用' : '禁用' }
  },
  {
    title: '手机号码',
    dataIndex: 'mobile'
  },
  {
    title: '创建时间',
    dataIndex: 'createdTime',
    customRender: (value) => { return moment(value).format('YYYY-MM-DD HH:mm:ss') }
  }, {
    title: '操作',
    width: '300px',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'UserList',
  layout: 'basic-layout',
  components: {
    STable,
    PageView
  },
  data () {
    return {
      description: '列表使用场景：后台管理中的权限管理以及角色管理，可用于基于 RBAC 设计的角色权限控制，颗粒度细到每一个操作类型。',
      // 向后端拉取可以本用户分配的角色列表
      permissionList: null,
      permissionMap: null,
      visible: false,
      resetVisible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      form: this.$form.createForm(this),
      mdl: {
        username: ''
      },
      resetMdl: {},
      resetRecord: {},
      isCreate: false,
      // 查询参数
      queryParam: {},
      // 表头
      columnsBase,
      columns: [...columnsBase],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const that = this
        return that.$authApi.getUserByPages(parameter.pageNo, parameter.pageSize, { ...this.queryParam }).then(res => {
          if (!res.data.total) {
            res.data.total = (res.data.data || res.data.records || []).length
          }
          console.log('res.data', res.data)
          return res.data
        })
      },

      selectedRowKeys: [],
      selectedRows: []
    }
  },

  computed: {
    ...mapState({
      user: state => state.auth && state.auth.user || {}
    })
  },

  activated () {
    this.loadPermissionList()
    this.$refs.table.refresh(true)
  },
  methods: {
    moment,
    loadPermissionList () {
      // permissionList
      const that = this
      return that.$authApi.getRoles()
        .then(res => {
          console.log('getRoles', res)
          this.permissionList = res.data
          this.permissionMap = {}
          res.data.forEach(item => {
            this.permissionMap[item.role.code] = item.role.name
          })
        })
    },
    handleDelUser (record) {
      this.$teacherApi.getByUser(record.id).then(res => {
        if (res.data.id == null) {
          return this.$authApi.delUser(record.id)
            .then(res => {
              console.log('deluser', res)
              this.$refs.table.refresh(true)
            })
        } else {
          this.$message.error('该用户有协助员工角色，请到员工管理板块进行删除')
        }
      })
    },
    handleCreate () {
      this.mdl = {
        username: ''
      }
      this.visible = true
      this.isCreate = true
    },
    handleEdit (record) {
      this.mdl = Object.assign({}, record)
      this.visible = true
      this.isCreate = false
    },
    handleReset (record) {
      if (this.resetMdl.password !== this.resetMdl.password2) {
        this.$message.error('两次输入的密码不一致，请重新输入')
        return
      }
      this.resetMdl.userId = this.resetRecord.id
      this.$authApi.resetPassword(this.resetMdl).then(res => {
        if (res.code === '000000') {
          this.$message.success('修改密码成功')
        } else {
          this.$message.error(res.mesg || res.data)
        }
        this.resetVisible = false
      })
    },
    handleOk () {
      const that = this

      // if (mdl && !mdl.scope || !mdl.scope.length) return this.$notification['error']({ message: '请赋予角色' })
      if (this.isCreate) {
        this.form.validateFields((err, values) => {
          var is_employee = values.scope.indexOf('DEVELOPER')
          var is_teacher = values.scope.indexOf('TEACHER')
          if (is_employee !== -1 && is_teacher !== -1) {
            this.$message.error('角色不能同时为老师和员工')
          } else if (is_employee) {
            // this.$message.error('是员工')
          } else if (is_teacher) {
            // this.$message.error('是教师')
          }
          if (err === null) {
            values.password = 'abc123'
            values.nickname = values.username
            that.$authApi.saveUserForm(values)
              .then(res => {
                if (res.code === '000000') {
                  this.$message.success('创建用户成功')
                  that.$refs.table.refresh(true)
                  that.visible = false
                } else {
                  this.$message.error(res.data || res.mesg)
                }
              })
          }
        })
      } else {
        this.form.validateFields((err, values) => {
          if (err === null) {
            var is_employee = values.scope.indexOf('DEVELOPER')
            var is_teacher = values.scope.indexOf('TEACHER')
            if (is_employee !== -1 && is_teacher !== -1) {
              this.$message.error('角色不能同时为老师和员工')
            } else if (is_employee) {
            // this.$message.error('是员工')
            } else if (is_teacher) {
            // this.$message.error('是教师')
            }
            that.$authApi.updateUser(this.mdl.id, values)
              .then(res => {
                if (res.code === '000000') {
                  this.$message.success('更新用户成功')
                  that.$refs.table.refresh(true)
                  that.visible = false
                } else {
                  this.$message.error(res.data || res.mesg)
                }
              })
          }
        })
      }
    },
    handleCancel () {
      this.visible = false
      this.resetVisible = false
    },
    resetPassword (record) {
      this.resetVisible = true
      this.resetMdl = {}
      this.resetRecord = record
    },
    toggle (record) {
      const that = this
      const params = {
        id: record.id,
        accountNonLocked: !record.accountNonLocked
      }
      this.$authApi.toggleUser(params).then(res => {
        that.$refs.table.refresh(true)
      })
    },
    onChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetForm () {
      this.queryParam = {}
    }
  }
}
</script>

<style lang="less" scoped>
.table-page-search-wrapper {
  .ant-form {
    .ant-row {
      .table-page-search-submitButtons,
      .ant-row.ant-form-item {
        margin-bottom: 0;
      }
    }
  }
}
</style>
